﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace AKJ.Sharepoint.Branding.HTTPModules
{
    /// <summary>
    /// This Response filter can inject a CSS entry in the <head> tag
    /// </summary>
    public class CSSInjectFilter : Stream
    {
        Stream responseStream;
        StringBuilder responseHtml;
        string cssPath = "";
        long position;

        public string CssPath
        {
            set { cssPath = value; }
            get { return cssPath; }
        }

        public CSSInjectFilter(Stream inputStream)
        {
            responseStream = inputStream;
            responseHtml = new StringBuilder();
        }

        #region Boilerplate overrides
        public override bool CanRead
        {
            get { return true; }
        }

        public override bool CanSeek
        {
            get { return true; }
        }

        public override bool CanWrite
        {
            get { return true; }
        }

        public override void Close()
        {
            responseStream.Close();
        }

        public override void Flush()
        {
            responseStream.Flush();
        }

        public override long Length
        {
            get { return 0; }
        }

        public override long Position
        {
            get { return position; }
            set { position = value; }
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return responseStream.Seek(offset, origin);
        }

        public override void SetLength(long length)
        {
            responseStream.SetLength(length);
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return responseStream.Read(buffer, offset, count);
        }
        #endregion

        public override void Write(byte[] buffer, int offset, int count)
        {
            string strBuffer = System.Text.UTF8Encoding.UTF8.GetString(buffer, offset, count);

            // ---------------------------------
            // Wait for the closing </html> tag
            // ---------------------------------
            Regex eof = new Regex("</html>", RegexOptions.IgnoreCase);

            if (!eof.IsMatch(strBuffer))
            {
                responseHtml.Append(strBuffer);
            }
            else
            {
                string css = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\"/>", CssPath);

                responseHtml.Append(strBuffer);
                string finalHtml = responseHtml.ToString().Replace("</head>", @"
" + css + @"
</head>");

                // Transform the response and write it back out
                byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(finalHtml);

                responseStream.Write(data, 0, data.Length);
            }
        }
    }
}
